package top.heathylife.pagehelperx.comparator;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import top.heathylife.pagehelperx.other.Get;
import top.heathylife.pagehelperx.other.TypeFunction;
import top.heathylife.pagehelperx.converter.BetweenConverter;

import java.math.BigDecimal;
import java.util.Comparator;

/**
 * 升序比较器
 *
 * @author maoxiaomeng
 */
public class AscComparator<T> implements Comparator<T> {

    private TypeFunction<T, ?> key;

    public void setKey(TypeFunction<T, ?> key) {
        this.key = key;
    }

    public static <T> AscComparator<T> getInstance(TypeFunction<T, ?> key) {
        AscComparator<T> tAscComparator = new AscComparator<>();
        tAscComparator.setKey(key);
        return tAscComparator;
    }


    @Override
    public int compare(T o1, T o2) {

        JSON parse1 = JSONUtil.parse(o1);
        Object obj1 = parse1.getByPath(Get.name(key));
        JSON parse2 = JSONUtil.parse(o2);
        Object obj2 = parse2.getByPath(Get.name(key));
        String str1 = StrUtil.toString(obj1);
        String str2 = StrUtil.toString(obj2);
        if (obj1 == null && obj2 == null) {
            return 1;
        }
        if (obj1 == null) {
            return -1;
        }
        if (obj2 == null) {
            return 1;
        }
        if (str1.equals(str2)) {
            return 0;
        }

        //数字比较
        if (NumberUtil.isNumber(str1) && NumberUtil.isNumber(StrUtil.toString(str2))) {
            BigDecimal b1 = new BigDecimal(str1);
            BigDecimal b2 = new BigDecimal(str2);
            return b1.subtract(b2).toBigInteger().intValue();
        }

        //日期比较
        if (BetweenConverter.isValidDateTime(str1) && BetweenConverter.isValidDateTime(str2)) {
            if (str1.contains("T")) {
                str1 = str1.replace("T", " ");
            }
            if (str2.contains("T")) {
                str2 = str2.replace("T", " ");
            }
            return DateUtil.parseDateTime(str1).isAfter(DateUtil.parseDateTime(str2)) ? 1 : -1;
        }
        if (BetweenConverter.isValidDate(str1) && BetweenConverter.isValidDate(str2)) {
            return DateUtil.parseDate(str1).isAfter(DateUtil.parseDate(str2)) ? 1 : -1;
        }
        //字符串比较
        return str1.compareTo(str2);
    }
}
